package com.wangwei.authoritySystem.controller;

import com.wangwei.authoritySystem.common.Result;
import com.wangwei.authoritySystem.pojo.Department;
import com.wangwei.authoritySystem.service.DepartmentService;
import com.wangwei.authoritySystem.vo.DepartmentQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/department")
public class DepartmentController {
    @Autowired
    DepartmentService departmentService;
    /**
     * 查询部门列表
     */
    @GetMapping("/list")
    public Result list(DepartmentQueryVo departmentQueryVo){
        List<Department> departmentList = departmentService.findDepartmentList(departmentQueryVo);
        return Result.success(departmentList);
    }

    /**
     * 查询上级部门列表
     */
    @GetMapping("/parent/list")
    public Result getParentDepartment(){
        List<Department> departmentList = departmentService.findParentDepartment();
        return Result.success(departmentList);
    }

    /**
     * 添加部门
     * @param department
     * @return
     */
    @PostMapping("/add")
    public Result add(@RequestBody Department department){
        if(departmentService.save(department)){
            return Result.success(200,"添加部门成功",department);
        }
        return Result.fail("添加部门失败");
    }

    /**
     * 修改部门
     * @param department
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody Department department){
        if(departmentService.updateById(department)){
            return Result.success(200,"修改部门成功",department);
        }
        return Result.fail("修改部门失败");
    }

    /**
     * 检查某个部门下是否有子部门
     * @param id
     * @return
     */
    @GetMapping("/check/{id}")
    public Result check(@PathVariable Long id){
        if(departmentService.checkPid(id)>0){
            return Result.exist("该部门下存在子部门，无法删除",true);
        }
        if(departmentService.checkUser(id)>0){
            return Result.exist("该部门下存在用户，无法删除",true);
        }
        return Result.exist("可删除",false);
    }



    /**
     * 删除部门
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Long id){
        if(departmentService.removeById(id)){
            return Result.success(200,"删除部门成功",null);
        }
        return Result.fail("删除部门失败");
    }
}
